package com.hillky.compress;

import com.hillky.compress.impl.GzipCompressor;
import com.hillky.config.ObjectWrapper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class CompressorFactory {


    private  static ConcurrentHashMap<String, ObjectWrapper<Compressor>> COMPRESS_CACHE = new ConcurrentHashMap<>();
    private  static ConcurrentHashMap<Byte,ObjectWrapper<Compressor>> COMPRESS_CACHE_CODE = new ConcurrentHashMap<>();

    static {
        ObjectWrapper gzip = new ObjectWrapper<Compressor>((byte) 1, "gzip", new GzipCompressor());
        COMPRESS_CACHE.put("gzip",gzip);
        COMPRESS_CACHE_CODE.put((byte)1,gzip);
    }

    /**
     * 使用工厂方法获取一个CompressorWrapper
     * @param compressType 压缩类型
     * @return 包装类
     */
    public static ObjectWrapper<Compressor> getCompressor(String compressType) {
        ObjectWrapper<Compressor> compressorObjectWrapper = COMPRESS_CACHE.get(compressType);
        if(compressorObjectWrapper==null){
            log.error("未找到你配置的【{}】压缩算法，默认选用gzip压缩",compressType);
            return COMPRESS_CACHE.get("gzip");
        }
        return COMPRESS_CACHE.get(compressType);
    }


    public static ObjectWrapper<Compressor> getCompressor(Byte compressorCode) {
        ObjectWrapper<Compressor> compressorObjectWrapper = COMPRESS_CACHE_CODE.get(compressorCode);
        if(compressorObjectWrapper==null){
            log.error("未找到你配置的编号为【{}】压缩算法，默认选用gzip压缩",compressorCode);
            return COMPRESS_CACHE.get("gzip");
        }
        return COMPRESS_CACHE_CODE.get(compressorCode);
    }

    /**
     * 给工程新增一个压缩实现方式
     * @param compressorObjectWrapper 压缩类型的包装
     */
    public static void addCompressor(ObjectWrapper<Compressor> compressorObjectWrapper){
        COMPRESS_CACHE.put(compressorObjectWrapper.getName(),compressorObjectWrapper);
        COMPRESS_CACHE_CODE.put(compressorObjectWrapper.getCode(),compressorObjectWrapper);
    }
}
